<template>
  <div class="container">
    <el-row>
      <el-col>
        <section class="toolbox">
          <date-range-picker
            v-model="datePicker1"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            value-format="yyyy-MM-dd"
            class="w-280"
            @change="timeChange"
          />
          <el-button type="primary" plain size="small" @click="search"
            >搜索</el-button
          >
        </section>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="金币和零钱统计报表" name="first">
            <el-card class="box-card">
              <div>
                <h3>金币和零钱统计报表</h3>
                <el-button
                  class="export-btn fr"
                  type="primary"
                  size="small"
                  @click="toExport('coinCash')"
                >
                  导出</el-button
                >
                <el-table
                  :data="tableData1"
                  border
                  style="width: 100%"
                  show-summary
                  :summary-method="summaryCoinChangeTable"
                >
                  <el-table-column prop="date" label="时间" />
                  <el-table-column
                    prop="newCoin"
                    width="180"
                    label="会员新增金币总数（个）"
                  />
                  <el-table-column
                    prop="consumeCoin"
                    label="会员消耗金币总数（个）"
                  />
                  <el-table-column
                    prop="sumCoin"
                    label="会员金币净增量（个）"
                  />
                  <el-table-column
                    prop="newCash"
                    label="会员新增零钱总金额（美元）"
                  />
                  <el-table-column
                    prop="totalCurrentCash"
                    label="累计在库零钱总金额（美元）"
                  />
                  <el-table-column
                    prop="applyCount"
                    label="申请提现和零钱充值的总订单量（条）"
                  />
                  <el-table-column
                    prop="applyCash"
                    label="申请提现和零钱充值的零钱总额（美元）"
                  />
                  <el-table-column
                    prop="totalExpendCash"
                    label="系统实际支出总金额（美元）"
                  />
                  <el-table-column
                    prop="memberAvgGetCash"
                    width="190"
                    label="实际人均获取零钱（美元）"
                  />
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>

          <el-tab-pane label="零钱提现统计报表" name="second">
            <el-card class="box-card">
              <div>
                <h3>零钱提现统计报表</h3>
                <el-button
                  class="export-btn fr"
                  type="primary"
                  size="small"
                  @click="toExport('cashWithdrawal')"
                >
                  导出</el-button
                >
                <el-table
                  :data="tableData2"
                  border
                  style="width: 100%"
                  show-summary
                  :summary-method="summaryTable"
                >
                  <el-table-column prop="date" label="时间" />
                  <el-table-column
                    prop="withdrawCount"
                    label="申请提现订单量（条）"
                  />
                  <el-table-column
                    prop="withdrawCash"
                    label="申请提现金额（美元）"
                  />
                  <el-table-column
                    prop="successWithdrawCount"
                    label="成功提现订单量（条）"
                  />
                  <el-table-column
                    prop="successWithdrawCash"
                    label="成功提现金额（美元）"
                  />
                  <el-table-column
                    prop="totalWithdrawCash"
                    label="累计提现金额（美元）"
                  />
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>

          <el-tab-pane label="手机充值统计报表" name="three">
            <el-card class="box-card">
              <div>
                <h3>手机充值统计报表</h3>
                <el-button
                  class="export-btn fr"
                  type="primary"
                  size="small"
                  @click="toExport('phoneReplenishing')"
                >
                  导出</el-button
                >
                <el-table
                  :data="tableData3"
                  border
                  style="width: 100%"
                  show-summary
                  :summary-method="summaryTable"
                >
                  <el-table-column prop="date" label="时间" />
                  <el-table-column
                    prop="phoneRechargeCount"
                    label="手机充值订单量（条）"
                  />
                  <el-table-column
                    prop="cashRechargeCount"
                    label="申请零钱充值订单量（条）"
                  />
                  <el-table-column
                    prop="successCashRechargeCount"
                    label="零钱充值成功订单量（条）"
                  />
                  <el-table-column
                    prop="successCashRechargeCountPercent"
                    label="零钱充值成功订单占比"
                  />
                  <el-table-column
                    prop="successPhoneRechargeCash"
                    label="充值成功金额（美元）"
                  />
                  <el-table-column
                    prop="successCashRechargeCash"
                    label="零钱充值成功金额（美元）"
                  />
                  <el-table-column
                    prop="successCashRechargeCashPercent"
                    label="零钱充值成功金额占比"
                  />
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>

          <el-tab-pane label="风控系统报表" name="four">
            <el-card class="box-card">
              <div>
                <h3>风控系统报表</h3>
                <el-button
                  class="export-btn fr"
                  type="primary"
                  size="small"
                  @click="toExport('riskManagement')"
                >
                  导出</el-button
                >
                <el-table
                  :data="tableData4"
                  border
                  style="width: 100%"
                  show-summary
                  :summary-method="summaryTable"
                >
                  <el-table-column prop="date" label="时间" />
                  <el-table-column
                    prop="newNotSureCount"
                    label="新增疑似异常会员数（人）"
                  />
                  <el-table-column
                    prop="newGreyCount"
                    label="新增灰名单人数（人）"
                  />
                  <el-table-column
                    prop="newBlackCount"
                    label="新增黑名单人数（人）"
                  />
                  <el-table-column
                    prop="newWhiteCount"
                    label="新增白名单会员数（人）"
                  />
                  <el-table-column
                    prop="systemRefuseCash"
                    label="系统拒绝审核金额（美元）"
                  />
                  <el-table-column
                    prop="manRefuseCash"
                    label="人工拒绝审核金额（美元）"
                  />
                  <el-table-column
                    prop="totalRefuseCash"
                    label="拒绝审核金额（美元）"
                  />
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { dateShortcutKeyJS } from '@/mixins/index.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';
import {
  getCoinCashAnalyzeApi,
  getCashWithdrawAnalyzeApi,
  getPhoneRechargeAnalyzeApi,
  getMemberStatusAnalyzeApi
} from '@/api/integral.js';
import timeUtils from '@/utils/timeHandle.js';
const tableHead = {
  coinCash: [
    {
      label: '时间',
      prop: 'date'
    },
    {
      label: '会员新增金币总数（个）',
      prop: 'newCoin'
    },
    {
      label: '会员消耗金币总数（个）',
      prop: 'consumeCoin'
    },
    {
      label: '会员金币净增量（个）',
      prop: 'sumCoin'
    },
    {
      label: '会员新增零钱总金额（美元）',
      prop: 'newCash'
    },
    {
      label: '累计在库零钱总金额（美元）',
      prop: 'totalCurrentCash'
    },
    {
      label: '申请提现和零钱充值的总订单量（条）',
      prop: 'applyCount'
    },
    {
      label: '申请提现和零钱充值的零钱总额（美元）',
      prop: 'applyCash'
    },
    {
      label: '系统实际支出总金额（美元）',
      prop: 'totalExpendCash'
    },
    {
      label: '实际人均获取零钱（美元）',
      prop: 'memberAvgGetCash'
    }
  ],
  cashWithdrawal: [
    {
      label: '时间',
      prop: 'date'
    },
    {
      label: '申请提现订单量（条）',
      prop: 'withdrawCount'
    },
    {
      label: '申请提现金额（美元）',
      prop: 'withdrawCash'
    },
    {
      label: '成功提现订单量（条）',
      prop: 'successWithdrawCount'
    },
    {
      label: '成功提现金额（美元）',
      prop: 'successWithdrawCash'
    },
    {
      label: '累计提现金额（美元）',
      prop: 'totalWithdrawCash'
    }
  ],
  phoneReplenishing: [
    {
      label: '时间',
      prop: 'date'
    },
    {
      label: '手机充值订单量（条）',
      prop: 'phoneRechargeCount'
    },
    {
      label: '申请零钱充值订单量（条）',
      prop: 'cashRechargeCount'
    },
    {
      label: '零钱充值成功订单量（条）',
      prop: 'successCashRechargeCount'
    },
    {
      label: '零钱充值成功订单占比',
      prop: 'successCashRechargeCountPercent'
    },
    {
      label: '充值成功金额（美元）',
      prop: 'successPhoneRechargeCash'
    },
    {
      label: '零钱充值成功金额（美元）',
      prop: 'successCashRechargeCash'
    },
    {
      label: '零钱充值成功金额占比',
      prop: 'successCashRechargeCashPercent'
    }
  ],
  riskManagement: [
    {
      label: '时间',
      prop: 'date'
    },
    {
      label: '新增疑似异常会员数（人）',
      prop: 'newNotSureCount'
    },
    {
      label: '新增灰名单人数（人）',
      prop: 'newGreyCount'
    },
    {
      label: '新增黑名单人数（人）',
      prop: 'newBlackCount'
    },
    {
      label: '新增白名单会员数（人）',
      prop: 'newWhiteCount'
    },
    {
      label: '系统拒绝审核金额（美元）',
      prop: 'systemRefuseCash'
    },
    {
      label: '人工拒绝审核金额（美元）',
      prop: 'manRefuseCash'
    },
    {
      label: '拒绝审核金额（美元）',
      prop: 'totalRefuseCash'
    }
  ]
};
export default {
  name: 'IntegralList',
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      activeName: 'first',
      tableName: {
        coinCash: '金币和零钱统计报表',
        cashWithdrawal: '零钱提现统计报表',
        phoneReplenishing: '手机充值统计报表',
        riskManagement: '风控系统报表'
      },
      tableHead: tableHead,
      tableData1: [],
      tableData2: [],
      tableData3: [],
      tableData4: [],
      datePicker1: [
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],
      listQuery: {
        startTime: timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        endTime: timeUtils.timeHandle(new Date().getTime(), 'date'),
        dateType: 1
      },

      exportData: {
        // 导出表格数据
        coinCash: [],
        cashWithdrawal: [],
        phoneReplenishing: [],
        riskManagement: []
      }
    };
  },
  created() {
    this.search();
  },
  methods: {
    timeChange(time) {
      if (!time) return;
      const startTime = Date.parse(time[0]);
      const endTime = Date.parse(time[1]);
      const Days = Math.floor(
        Math.abs(endTime - startTime) / (24 * 3600 * 1000)
      );
      if (Days <= 31) {
        this.listQuery.dateType = 1;
      } else if (Days > 31 && Days <= 42) {
        this.listQuery.dateType = 2;
      } else if (Days > 42) {
        this.listQuery.dateType = 3;
      }
    },
    search() {
      if (!this.datePicker1) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }
      this.listQuery.startTime = this.datePicker1[0];
      this.listQuery.endTime = this.datePicker1[1];

      this.getList1();
      this.getList2();
      this.getList3();
      this.getList4();
    },
    getList1() {
      getCoinCashAnalyzeApi(this.listQuery).then(res => {
        if (res.code == 200) {
          this.exportData.coinCash = this.tableData1 = res.data || [];
        }
      });
    },
    getList2() {
      getCashWithdrawAnalyzeApi(this.listQuery).then(res => {
        if (res.code == 200) {
          this.exportData.cashWithdrawal = this.tableData2 = res.data || [];
        }
      });
    },
    getList3() {
      getPhoneRechargeAnalyzeApi(this.listQuery).then(res => {
        if (res.code == 200) {
          this.exportData.phoneReplenishing = this.tableData3 = res.data || [];
        }
      });
    },
    getList4() {
      getMemberStatusAnalyzeApi(this.listQuery).then(res => {
        if (res.code == 200) {
          this.exportData.riskManagement = this.tableData4 = res.data || [];
        }
      });
    },

    summaryCoinChangeTable({ columns, data }) {
      const summary = this.summaryTable({ columns, data });
      if (summary.length > 1) {
        const sum = prop => data.map(t => t[prop]).reduce((s, n) => s + n, 0);
        const totalExpand = sum('totalExpendCash');
        const totalExpendMemberCount = sum('memberCount');
        const avg = totalExpand / totalExpendMemberCount;
        const avgValid = Number.isNaN(avg) ? 0 : avg;
        summary[summary.length - 1] = avgValid.toFixed(2);
      }
      return summary;
    },

    summaryTable({ columns, data }) {
      const group = (list, keys) =>
        list.reduce(
          (r, t) => keys.map((k, i) => (r[i] ? r[i].concat([t[k]]) : [t[k]])),
          []
        );
      const keys = columns.map(this.$pick('property'));
      const columnData = group(data, keys);
      const sum = list => list.reduce((r, t) => r + t, 0);
      const summaryData = columnData
        .map(l =>
          l.length && l.every(t => !Number.isNaN(Number(t))) ? sum(l) : '-'
        )
        .map(n => (typeof n === 'number' ? n.toFixed(2) : n));
      return [this.$t('subtotal')].concat(summaryData.slice(1));
    },

    toExport(exportName) {
      const exprtTime = timeUtils.timeHandle(new Date().getTime(), 'date');
      const tHeader = this.tableHead[exportName].map(item => item.label);
      const tKey = this.tableHead[exportName].map(item => item.prop);
      const data = formatJson(tKey, this.exportData[exportName]); // 数据格式化
      const fileName = this.tableName[exportName] + exprtTime;
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px 20px;
  .toolbox {
    float: right;
    margin-top: 14px;
    .export {
      margin-left: 10px;
      vertical-align: top;
    }
  }
  .w-280 {
    width: 280px;
  }
  .box-card {
    h3 {
      font-size: 24px;
      line-height: 48px;
      text-align: center;
    }
    .export-btn {
      margin-bottom: 10px;
    }
  }
}
</style>
